import hashlib  # 加密相关
import time
from datetime import datetime, timedelta
import jwt
from flask import Blueprint, request, current_app
import requests
from apps.user import to_user_db
from utilsapp.excel_util import db_insert
from utilsapp.mysql_con import db_connect, db_list
from utilsapp.mysql_con import db_operation

appuser = Blueprint("appuser", __name__)


# 登录
@appuser.route("/login", methods=["POST"])
def user_login():
    user_name = request.json.get("user_name")
    pwd_input = request.json.get("password")
    source = request.json["source"] if "source" in request.json else ""  # 来源
    token_input = request.json["access_token"] if "access_token" in request.json else ""
    is_token_login = token_input and len(token_input) > 0
    ip = request.remote_addr
    if is_token_login:
        pwd_input = "1"
        if not user_name:
            return {"code": -1, "msg": "自动登录失败"}
    sql = """SELECT userinfo.id,userinfo.role_id,userinfo.notify,userinfo.speech,userinfo.mail,userinfo.message,userinfo.user_name,userinfo.nick_name,userinfo.password,role.operate,role.desc as user_role,
    role.dataId,regionlevel.type from userinfo LEFT JOIN role on userinfo.role_id = role.id left JOIN regionlevel on 
    role.dataId = regionlevel.id where userinfo.user_name = '{}'""".format(
        user_name
    )
    res = db_connect(sql)
    if res["code"] == -1:  # 数据库连接失败
        return res
    else:  # 连接成功验证密码
        if not res["data"]:
            return {"sataus": -1, "msg": "用户名不存在"}
        else:
            password = res["data"][0]["password"]
            role_id = res["data"][0]["role_id"]
            userDict = {
                "id": res["data"][0]["id"],
                "user_name": res["data"][0]["user_name"],
                "user_role": res["data"][0]["user_role"],
                "dataId": res["data"][0]["dataId"],
                "nick_name": res["data"][0]["nick_name"],
                "type": res["data"][0]["type"],
                "notify": res["data"][0]["notify"],
                "speech": res["data"][0]["speech"],
                "mail": res["data"][0]["mail"],
                "message": res["data"][0]["message"],
                "operate": res["data"][0]["operate"],
            }
            now = int(time.time())
            time_tuple = time.localtime(now)
            bj_time = time.strftime("%Y-%m-%d %H:%M:%S", time_tuple)
            userDict["user_time"] = bj_time
            hl = hashlib.md5()  # 加密
            hl.update(pwd_input.encode(encoding="utf-8"))
            if hl.hexdigest() == password or is_token_login:  # 密码验证成功
                login_token = create_token(
                    user_name, role_id, current_app.config["settings"]["SECRET_KEY"]
                )
                # 更新用户的login_token
                ua = request.headers["User-Agent"].lower()
                if "android" in ua or "iphone" in ua or "mobile" in ua:
                    token = "app_token"
                else:
                    token = "login_token"
                sql1 = f'UPDATE userinfo SET {token} = "{login_token}"where user_name= "{user_name}"'
                res = db_operation(sql1)  # 更新用户登录状态，token
                if res["Affected_rows"] >= 1:
                    return {
                        "status": 200,
                        "msg": "登录成功",
                        "data": {"userInfo": userDict, "token": login_token},
                    }
                else:
                    return {"status": 203, "msg": "登录失败"}
            else:  # 密码验证失败
                return {"status": 202, "msg": "账号或密码错误"}


# 生成token
def create_token(user_name, role_id, key):
    payload = {
        "exp": datetime.now()
        + timedelta(hours=current_app.config["settings"]["over_time"]),
        "user_name": user_name,
        "role_id": role_id,
    }
    token = str(jwt.encode(payload=payload, key=key, algorithm="HS256"))
    return token


def get_userList():
    try:
        o = {"systemCode": "044221b7ccc04262a9353facd0553279"}
        res = requests.get(
            "http://171.221.216.84:18000/api/ivystar-user/api/userList",
            params=o,
            timeout=5,
        )
        if res.status_code != 200:
            print("同步用户请求失败", res.status_code)
            return
        j = res.json()
        if not j["success"]:
            print("同步用户数据失败", res.text)
            return
        print("获取用户数据成功")

        print("获取用户数据成功")
        dbres = db_list("SELECT user_name FROM userinfo")
        old_ids = [] if dbres["code"] != 0 else [t["user_name"] for t in dbres["data"]]
        add_models = [to_user_db(n) for n in j["data"] if n["account"] not in old_ids]
        if len(add_models) <= 0:
            print("同步用户数据成功", "暂无新数据同步")
            return
        dbres = db_insert("userinfo", add_models)
        if dbres["code"] == 0:
            print("同步用户数据成功", "影响行数", dbres["Affected_rows"])
            return

    except Exception as e:
        print("login_token 异常", e)


def get_username_bytoken(token):
    try:
        o = {"systemCode": "044221b7ccc04262a9353facd0553279", "token": token}
        res = requests.get(
            "http://171.221.216.84:18000/api/ivystar-user/api/getUserByToken",
            params=o,
            timeout=5,
        )
        if res.status_code != 200:
            return None
        j = res.json()
        print(j, "jjjjj")
        if j["success"]:
            return j["data"]["account"]
        return None
    except Exception as e:
        print("login_token 异常", e)
        return None


# 验证token
# def verify_token(token, key):
#
#     try:
#         # 解析token拿到用户名和角色id
#         info = jwt.decode(token, key, algorithms='HS256')
#
#         exp = info['exp']
#         role_id = info['role_id']
#         now = int(time.time())
#         user_name = info['user_name']
#         sql = f'SELECT app_token FROM userinfo where user_name= "{user_name}"'
#         sql_1 = f"""SELECT r.dataId ,r.desc,r.permissionIdList FROM role r,regionlevel l
#         where  r.dataId=l.id AND r.id= {role_id}"""
#
#         res = db_connect(sql_1)
#
#         past_token = db_connect(sql)['data'][0]['app_token']
#
#         if not res['data']:
#             flag = {
#                 'dataId': 0
#             }
#         else:
#             flag = res['data'][0]
#         if now > exp:  # token过期
#             return {
#                 'msg': '登录状态过期',
#                 'status': -1000,
#             }
#         else:
#             if past_token == token:
#                 return {
#                     'msg': 'token认证成功',
#                     'status':200,
#                     "flag": flag
#                 }
#             else:
#                 return {
#                     'msg': '账号已在其他设备登录',
#                     'status': -1000,
#                 }
#     except exceptions.ExpiredSignatureError:  # 'token已失效'

#         return {
#             'msg': 'token已失效',
#             'status': -1000,
#         }

#     except jwt.DecodeError:  # 'token认证失败'

#         return {
#             'msg': 'token认证失败',
#             'status': -1000,
#         }

#     except jwt.InvalidTokenError:  # '非法的token'

#         return {
#             'msg': '非法的token',
#             'status': -1000,
#         }
